package com.jike.noobmoney.util;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.text.TextUtils;

import com.toomee.mengplus.common.utils.StringUtils;

import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author xuke
 * @date 2017/3/7  17:19
 */
public class ComUtils {

    /**
     * @param mContext 上下文
     * @param type     类型  1.QQ聊天   2.QQ资料界面   3.QQ群资料界面
     * @param qqnum    QQ号
     */
    public static void startQQ(Context mContext, int type, String qqnum) {
        if (checkApkExist(mContext, "com.tencent.mobileqq")) {
            String url = "";
            switch (type) {
                case 1:
                    url = "mqqwpa://im/chat?chat_type=wpa&uin=" + qqnum;
                    break;
                case 2:
                    url = "mqqapi://card/show_pslcard?src_type=internal&version=1&uin=" + qqnum
                            + "&card_type=person&source=qrcode";
                    break;
                case 3:
                    url = "mqqapi://card/show_pslcard?src_type=internal&version=1&uin=" + qqnum
                            + "&card_type=group&source=qrcode";
                    break;
                default:
                    break;
            }
            mContext.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
        } else {
            ToastUtils.showLongToast("本机未安装QQ应用");
        }
    }

    /**
     * 检查是否安装QQ
     */
    public static boolean checkApkExist(Context context, String packageName) {
        if (packageName == null || "".equals(packageName))
            return false;
        try {
            ApplicationInfo info = context.getPackageManager().getApplicationInfo(packageName,
                    PackageManager.GET_UNINSTALLED_PACKAGES);
            return true;
        } catch (PackageManager.NameNotFoundException e) {
            return false;
        }
    }

    /**
     * 签到倒计时
     */
    public static String formatLongToTimeStr(Long l) {
        int hour = 0;
        int minute = 0;
        int second = 0;
        second = l.intValue();
        if (second > 60) {
            minute = second / 60;   //取整
            second = second % 60;   //取余
        }
        if (minute > 60) {
            hour = minute / 60;
            minute = minute % 60;
        }
        return "剩余：" + hour + "小时" + minute + "分" + second + "秒";
    }

    /**
     * 获取当前年月日,判断是否是同一天
     */
    public static String getDay() {
        @SuppressLint("SimpleDateFormat")
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        return df.format(new Date());
    }

    /**
     * double相减
     */
    public static Double sub(Double v1, Double v2) {
        BigDecimal b1 = new BigDecimal(v1.toString());
        BigDecimal b2 = new BigDecimal(v2.toString());
        return b1.subtract(b2).doubleValue();
    }

    /**
     * 推荐码字符串截取
     */
    public static String jiequ(String str) {
        String newStr = "";
        if (!TextUtils.isEmpty(str) && str.length() > 2) {
            String qian = str.substring(0, 2);
            String hou = str.substring(str.length() - 2, str.length());
            newStr = qian + "****" + hou;
        }
        return newStr;
    }

    /**
     * 手机号字符串截取
     */
    public static String jiequPhone(String str) {
        String newStr = "";
        if (!TextUtils.isEmpty(str) && str.length() > 4) {
            String qian = str.substring(0, 3);
            String hou = str.substring(str.length() - 4, str.length());
            newStr = qian + "****" + hou;
        }
        return newStr;
    }

    /**
     * 手机号字符串截取
     */
    public static String getPercent(String str) {
        Double rate =Double.parseDouble(str);
        NumberFormat num = NumberFormat.getPercentInstance();
        String rates = num.format(rate);
         return rates;
    }


    /**
     * 获取2的整数倍
     */

    public static double   getMaxMoney(double money)
    {
        if(money<2.0){
            return 0.0d;
        }else
        {
          double rimoney=  Math.floor(money);
          if(rimoney%2==1){
            return  rimoney-1;
          }else if(rimoney%2==0)
          {
            return  rimoney;

          }
        }
        return 0.0d;
    }
    /**
     *
     * 方法用途: 对所有传入参数按照字段名的Unicode码从小到大排序（字典序），并且生成url参数串<br>
     * 实现步骤: <br>
     *
     * @param paraMap   要排序的Map对象
     * @param urlEncode   是否需要URLENCODE
     * @param keyToLower    是否需要将Key转换为全小写
     *            true:key转化成小写，false:不转化
     * @return
     */
    public static String formatUrlMap(Map<String, String> paraMap, boolean urlEncode, boolean keyToLower)
    {
        String buff = "";
        Map<String, String> tmpMap = paraMap;
        try
        {
            List<Map.Entry<String, String>> infoIds = new ArrayList<Map.Entry<String, String>>(tmpMap.entrySet());
            // 对所有传入参数按照字段名的 ASCII 码从小到大排序（字典序）
            Collections.sort(infoIds, new Comparator<Map.Entry<String, String>>()
            {

                @Override
                public int compare(Map.Entry<String, String> o1, Map.Entry<String, String> o2)
                {
                    return (o1.getKey()).toString().compareTo(o2.getKey());
                }
            });
            // 构造URL 键值对的格式
            StringBuilder buf = new StringBuilder();
            for (Map.Entry<String, String> item : infoIds)
            {
                if (StringUtils.isNotEmpty(item.getKey()))
                {
                    String key = item.getKey();
                    String val = item.getValue();
                    if (urlEncode)
                    {
                        val = URLEncoder.encode(val, "utf-8");
                    }
                    if (keyToLower)
                    {
                        buf.append(key.toLowerCase() + "=" + val);
                    } else
                    {
                        buf.append(key + "=" + val);
                    }
                    buf.append("&");
                }

            }
            buff = buf.toString();
            if (buff.isEmpty() == false)
            {
                buff = buff.substring(0, buff.length() - 1);
            }

            StringBuffer sb=new StringBuffer(buff);
            sb.append("&");
            sb.append(Constant.keySecret);
            sb.append("=");
            sb.append(Constant.VALUE);
            Logger.e("xuke", "daiqian: " + sb.toString() );
            buff=MD5.GetMD5Code(sb.toString(),true);

            Logger.e("xuke", "最终: " + buff.toString());

        } catch (Exception e)
        {
            return null;
        }
        return buff;
    }


    /**
     * 时间戳转字符串
     */
    @SuppressLint("SimpleDateFormat")
    public static String longtimeToStr(long time) {
        return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(time * 1000));
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        //字典序列排序
        Map<String,String> paraMap = new HashMap<String,String>();
        paraMap.put("b","测试");
        paraMap.put("a", "测试");
        paraMap.put("d","测试");
        String url = ComUtils.formatUrlMap(paraMap, true, true);
        System.out.println(url);
    }

}
